package cringer::twittersearch;

# twittersearch.pm
# Exactly what the name implies

use JSON;

our $VERSION = '1.0';

sub said{
 my $self = $_[0];
 my $args = $_[1];
 my $me = $self->{nick};
 
 unless($args->{body} =~ /^twittersearch: ?(.*)$/){ # if this isn't a search query, we skip it.
  return;
 }

 my $q = $1;
 my @r; # set up the response array
 my $url = qq~http://search.twitter.com/search.json?rpp=4&q=~ . cringer::uriencode($q);
 my $r = $self->{ua}->get($url);
 my $json;
 eval { $json = from_json($r->decoded_content); };
 if($@ ne ''){
  print qq~\n================\nTwitter error:\n~ . $r->decoded_content . qq~\nError: $@\n================\n~;
  return qq~I'm sorry, but I encountered an error processing your query.~;
 }
 
my @results = @{$json->{results}};
my $numResults = @results;
push(@r, (($numResults) ? $numResults : qq~No~) . qq~ tweets found for "$q"~);
foreach my $result (@results){
 push(@r, qq~<$result->{from_user}> $result->{text} ( $result->{created_at} )~);
}
return @r;

}


sub commandList{ # a simple help routine to return a list of the commands we'll respond to
 return qq~twittersearch: [query]~;
}



return 1;